package com.xander.movieplayer.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Properties;

import static com.xander.movieplayer.util.VerifyCodeUtil.generateVerifyCode;
import static com.xander.movieplayer.util.VerifyCodeUtil.outputImage;

/**
 * Created by Xander on 2018-08-09.
 */
@Controller
@RequestMapping("resource")
public class ResourceController {

    @GetMapping("/auth")
    @ResponseBody
    public void authImage(HttpServletResponse response, HttpSession session) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image");
        session.removeAttribute("verCode");
        String code = generateVerifyCode(4);
        session.setAttribute("verCode", code.toLowerCase());
        //生成图片
        int w = 100, h = 40;
        outputImage(w, h, response.getOutputStream(), code);
    }

    @GetMapping("mp4/{path:.+}")
    @ResponseBody
    public void mp4(@PathVariable String path, HttpServletResponse response, String start) throws Exception {
        int startInt = 0;
        Properties p = new Properties();
        try {
            p.load(ResourceController.class.getResourceAsStream("/videopath.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String basePath = p.get("path").toString();
        String realPath = basePath + path.replaceAll(":", "/");
        response.setContentType("video/mp4");
        File file = new File(realPath);
        RandomAccessFile raf = null;
        int totalByte = 0;
        try {
            ServletOutputStream out = response.getOutputStream();
            raf = new RandomAccessFile(realPath, "r");
            totalByte = (int) raf.length();
            if (start != null && !" ".equals(start)) {
                try {
                    startInt = Integer.parseInt(start);
                    response.setContentLength(totalByte - startInt + 13);
                } catch (NumberFormatException e) {
                    startInt = 0;
                }
            } else {
                response.setContentLength(totalByte - startInt);
            }
            raf.skipBytes(startInt);//跳过时间轴前面的字节;
            byte[] b = new byte[4096];
            while (raf.read(b) != -1) {
                out.write(b);
            }
            out.flush();
        } catch (Exception e) {
            String simplename = e.getClass().getSimpleName();
            if (!"ClientAbortException".equals(simplename)) {
                e.printStackTrace();
            }//web端拖动时间轴总有连接被重置的异常，暂时还不知如何解决，可以此方式不输出异常
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @GetMapping("flv/{path:.+}")
    @ResponseBody
    public void flv(@PathVariable String path, HttpServletResponse response,String start) {
        int startInt = 0;
        Properties p = new Properties();
        try {
            p.load(ResourceController.class.getResourceAsStream("/videopath.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String basePath = p.get("path").toString();
        String realPath = basePath + path.replaceAll(":", "/");
        response.setContentType("video/flv");
        File file = new File(realPath);
        RandomAccessFile raf = null;
        int totalByte = 0;
        try {
            ServletOutputStream out = response.getOutputStream();
            raf = new RandomAccessFile(realPath, "r");
            totalByte = (int) raf.length();
            if (start != null && !" ".equals(start)) {
                try {
                    startInt = Integer.parseInt(start);
                    byte[] headData = new byte[]{'F', 'L', 'V', 1, 1, 0, 0, 0, 9, 0, 0, 0, 9}; //拖动时间轴后的response中头信息需写入该字节
                    out.write(headData);
                    response.setContentLength(totalByte - startInt + 13);
                } catch (NumberFormatException e) {
                    startInt = 0;
                }
            } else {
                response.setContentLength(totalByte - startInt);
            }
            raf.skipBytes(startInt);//跳过时间轴前面的字节;
            byte[] b = new byte[4096];
            while (raf.read(b) != -1) {
                out.write(b);
            }
            out.flush();
        } catch (Exception e) {
            String simplename = e.getClass().getSimpleName();
            if (!"ClientAbortException".equals(simplename)) {
                e.printStackTrace();
            }//web端拖动时间轴总有连接被重置的异常，暂时还不知如何解决，可以此方式不输出异常
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
